import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Typography, Button, Space, message, Spin, Empty, Tooltip, Modal } from 'antd';
import { ArrowLeftOutlined, SyncOutlined, ShareAltOutlined, CopyOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { getScanTask, getScanTaskPublic, startTask, cancelTask, retryTask, getTaskResults, TaskScanResults, downloadExcelReport, checkTaskCredentials } from '../../services/api';
import { EnhancedScanTaskResponse } from '../../types/taskDetail';
import TaskExecutionInfo from '../../components/TaskDetail/TaskExecutionInfo';
import TaskStatistics from '../../components/TaskDetail/TaskStatistics';
import EnhancedProblemTable from '../../components/shared/EnhancedProblemTable';
import { problemDataConverter } from '../../utils/problemDataConverter';
import { taskStatusPoller, TaskPollerInstance } from '../../utils/taskStatusPoller';
import { TaskProgressWebSocketClient } from '../../utils/TaskProgressWebSocketClient';
import './TaskDetail.css';

const { Title, Text } = Typography;

interface TaskDetailState {
  task: EnhancedScanTaskResponse | null;
  loading: boolean;
  actionLoading: boolean;
  credentialStatus: {
    loading: boolean;
    hasValidCredentials: boolean;
    gitCredentialValid: boolean;
    databaseCredentialValid: boolean;
    gitTokenExpiredAt?: string;
    databaseTokenExpiredAt?: string;
  };
  // WebSocket进度状态
  progressInfo: {
    isConnected: boolean;
    currentProgress: number;
    currentStage: string;
    currentMessage: string;
    isMilestone: boolean;
    milestoneTitle?: string;
    milestoneDescription?: string;
    estimatedRemainingSeconds?: number;
  };
  // 分享功能状态
  shareModal: {
    visible: boolean;
    publicUrl: string;
  };
}

interface TaskDetailProps {
  isPublicAccess?: boolean;
}

const TaskDetail: React.FC<TaskDetailProps> = ({ isPublicAccess = false }) => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  
  // 检查用户是否已登录，决定是否显示操作按钮
  const isUserLoggedIn = () => {
    // 公开访问模式下不显示任何操作按钮
    if (isPublicAccess) {
      return false;
    }
    const token = localStorage.getItem('token');
    const userInfo = localStorage.getItem('userInfo');
    return !!(token && userInfo);
  };
  
  const [state, setState] = useState<TaskDetailState>({
    task: null,
    loading: true,
    actionLoading: false,
    credentialStatus: {
      loading: false,
      hasValidCredentials: false,
      gitCredentialValid: false,
      databaseCredentialValid: false
    },
    progressInfo: {
      isConnected: false,
      currentProgress: 0,
      currentStage: '',
      currentMessage: '',
      isMilestone: false
    },
    shareModal: {
      visible: false,
      publicUrl: ''
    }
  });

  const [results, setResults] = useState<TaskScanResults | null>(null);
  const [resultsLoading, setResultsLoading] = useState<boolean>(false);
  const [isPolling, setIsPolling] = useState<boolean>(false);
  
  // 轮询实例管理
  const pollerInstanceRef = useRef<TaskPollerInstance | null>(null);
  
  // WebSocket客户端管理
  const wsClientRef = useRef<TaskProgressWebSocketClient | null>(null);

  // 处理进度更新
  const handleProgressUpdate = useCallback((progressInfo: any) => {
    console.log('收到进度更新:', progressInfo);
    
    setState(prev => ({
      ...prev,
      progressInfo: {
        isConnected: prev.progressInfo.isConnected,
        currentProgress: progressInfo.progress || 0,
        currentStage: progressInfo.currentStage || '',
        currentMessage: progressInfo.message || '',
        isMilestone: progressInfo.isMilestone || false,
        milestoneTitle: progressInfo.milestoneTitle,
        milestoneDescription: progressInfo.milestoneDescription,
        estimatedRemainingSeconds: progressInfo.estimatedRemainingSeconds
      }
    }));

    // 如果是里程碑，显示通知
    if (progressInfo.isMilestone && progressInfo.milestoneTitle) {
      message.success({
        content: `🎯 ${progressInfo.milestoneTitle}`,
        duration: 3,
        key: `milestone-${progressInfo.taskId}-${progressInfo.timestamp}`
      });
    }
  }, []);

  // WebSocket连接状态和进度处理
  const initWebSocket = useCallback(() => {
    if (!id) return;

    try {
      wsClientRef.current = new TaskProgressWebSocketClient();
      
      // 设置连接状态回调
      wsClientRef.current.setConnectionStatusCallback((connected: boolean) => {
        setState(prev => ({
          ...prev,
          progressInfo: {
            ...prev.progressInfo,
            isConnected: connected
          }
        }));

        if (connected) {
          console.log('WebSocket已连接，开始订阅任务进度:', id);
          // 订阅任务进度
          wsClientRef.current?.subscribeToTaskProgress(Number(id), handleProgressUpdate);
        } else {
          console.log('WebSocket连接断开');
        }
      });

      // 连接到服务器
      wsClientRef.current.connect();
    } catch (error) {
      console.error('WebSocket初始化失败:', error);
    }
  }, [id, handleProgressUpdate]);

  // 清理WebSocket
  const cleanupWebSocket = useCallback(() => {
    if (wsClientRef.current) {
      console.log('TaskDetail: 清理WebSocket连接');
      if (id) {
        wsClientRef.current.unsubscribeFromTaskProgress(Number(id));
      }
      wsClientRef.current.disconnect();
      wsClientRef.current = null;
    }
  }, [id]);

  /**
   * 清理轮询实例
   */
  const cleanupPoller = useCallback(() => {
    if (pollerInstanceRef.current) {
      console.log('TaskDetail: 清理轮询实例');
      pollerInstanceRef.current.stop();
      pollerInstanceRef.current = null;
      setIsPolling(false);
    }
  }, []);

  const loadTask = useCallback(async () => {
    try {
      setState(prev => ({ ...prev, loading: true }));
      // 根据访问模式选择API
      const response = isPublicAccess 
        ? await getScanTaskPublic(Number(id))
        : await getScanTask(Number(id));
      if (response.success) {
        setState(prev => ({ ...prev, task: response.data, loading: false }));
      } else {
        message.error(response.message || '获取任务详情失败');
        setState(prev => ({ ...prev, task: null, loading: false }));
      }
    } catch (error: any) {
      console.error('获取任务详情失败:', error);
      message.error(error.message || '获取任务详情失败');
      setState(prev => ({ ...prev, task: null, loading: false }));
    }
  }, [id, isPublicAccess]);

  /**
   * 检查任务凭证有效期
   */
  const checkCredentials = useCallback(async (task: EnhancedScanTaskResponse) => {
    // 只对需要凭证的任务类型进行检查
    if (!needsCredentialCheck(task)) {
      setState(prev => ({
        ...prev,
        credentialStatus: {
          loading: false,
          hasValidCredentials: true, // 不需要凭证的任务默认可以重试
          gitCredentialValid: true,
          databaseCredentialValid: true
        }
      }));
      return;
    }

    try {
      setState(prev => ({
        ...prev,
        credentialStatus: { ...prev.credentialStatus, loading: true }
      }));
      
      const response = await checkTaskCredentials(task.id);
      if (response.success) {
        setState(prev => ({
          ...prev,
          credentialStatus: {
            loading: false,
            ...response.data
          }
        }));
      } else {
        console.warn('检查凭证失败:', response.message);
        setState(prev => ({
          ...prev,
          credentialStatus: {
            loading: false,
            hasValidCredentials: false,
            gitCredentialValid: false,
            databaseCredentialValid: false
          }
        }));
      }
    } catch (error: any) {
      console.error('检查凭证异常:', error);
      setState(prev => ({
        ...prev,
        credentialStatus: {
          loading: false,
          hasValidCredentials: false,
          gitCredentialValid: false,
          databaseCredentialValid: false
        }
      }));
    }
  }, []);

  /**
   * 判断任务是否需要凭证检查
   */
  const needsCredentialCheck = (task: EnhancedScanTaskResponse): boolean => {
    const taskType = task.taskType;
    // MANUAL_SQL 不需要凭证，其他类型都需要
    return taskType !== 'MANUAL_SQL';
  };

  /**
   * 判断任务是否可以重试（包含凭证检查）
   */
  const canRetryWithCredentials = useCallback((task: EnhancedScanTaskResponse): boolean => {
    // 基本条件：任务状态允许重试
    const statusAllowsRetry = ['FAILED', 'COMPLETED', 'CANCELLED', 'SUCCESS'].includes(task.status);
    if (!statusAllowsRetry) {
      return false;
    }

    // 检查重试次数限制
    const currentRetryCount = task.retryCount || 0;
    const maxRetryCount = task.maxRetryCount || 3;
    if (currentRetryCount >= maxRetryCount) {
      return false;
    }

    // 检查凭证有效期
    if (needsCredentialCheck(task)) {
      return state.credentialStatus.hasValidCredentials && !state.credentialStatus.loading;
    }

    return true;
  }, [state.credentialStatus]);

  /**
   * 管理任务轮询
   */
  const manageTaskPolling = useCallback(() => {
    if (!state.task || !id) return;

    // 如果任务在运行中，或者是刚创建/待启动状态（可能正在启动），启动轮询
    if (state.task.status === 'RUNNING' || 
        state.task.status === 'PENDING' || 
        state.task.status === 'CREATED') {
      if (!pollerInstanceRef.current || !pollerInstanceRef.current.isRunning()) {
        console.log('TaskDetail: 启动任务轮询', state.task.id, '当前状态:', state.task.status);
        
        pollerInstanceRef.current = taskStatusPoller.createPoller(id, {
          interval: 3000, // 详情页面更快的轮询间隔：每3秒
          maxRetries: 5,
          onStatusChange: (updatedTask) => {
            console.log('TaskDetail: 任务状态更新', updatedTask.status);
            setState(prev => ({ 
              ...prev, 
              task: prev.task ? { ...prev.task, ...updatedTask } : null 
            }));
          },
          onComplete: (completedTask) => {
            console.log('TaskDetail: 任务完成', completedTask.status);
            setState(prev => ({ 
              ...prev, 
              task: prev.task ? { ...prev.task, ...completedTask } : null 
            }));
            cleanupPoller();
          },
          onError: (error) => {
            console.warn('TaskDetail: 轮询失败', error);
            cleanupPoller();
          }
        });

        pollerInstanceRef.current.start();
        setIsPolling(true);
      }
    } else {
      // 如果任务不在运行中，停止轮询
      cleanupPoller();
    }
  }, [state.task, id, cleanupPoller]);

  useEffect(() => {
    if (id) {
      loadTask();
    }
  }, [id, loadTask]);

  // 任务加载后检查凭证
  useEffect(() => {
    if (state.task) {
      checkCredentials(state.task);
    }
  }, [state.task?.id, checkCredentials]);

  // 组件卸载时清理轮询和WebSocket
  useEffect(() => {
    return () => {
      cleanupPoller();
      cleanupWebSocket();
    };
  }, [cleanupPoller, cleanupWebSocket]);

  // 初始化WebSocket连接
  useEffect(() => {
    if (id) {
      initWebSocket();
    }
  }, [id, initWebSocket]);

  // 当任务状态改变时，管理轮询
  useEffect(() => {
    if (state.task) {
      console.log('TaskDetail: 任务状态变化，管理轮询', state.task.status);
      manageTaskPolling();
      
      // 如果任务正在运行且WebSocket未连接，重新连接
      if ((state.task.status === 'RUNNING' || state.task.status === 'PENDING') && 
          !state.progressInfo.isConnected) {
        initWebSocket();
      }
    }
  }, [state.task?.status, manageTaskPolling, state.progressInfo.isConnected, initWebSocket]);

  useEffect(() => {
    // 当任务完成时拉取实际扫描结果
    if (state.task && (state.task.status === 'COMPLETED' || state.task.status === 'SUCCESS')) {
      fetchResults(state.task.id);
    } else {
      setResults(null);
    }
  }, [state.task]);

  const fetchResults = async (taskId: number) => {
    try {
      setResultsLoading(true);
      const res = await getTaskResults(taskId);
      if (res.success) {
        setResults(res.data || { totalFiles: 0, sqlStatements: 0, problemSqlStatements: 0, issues: [] });
      } else {
        message.warning(res.message || '未能获取扫描结果');
        setResults({ totalFiles: 0, sqlStatements: 0, problemSqlStatements: 0, issues: [] });
      }
    } catch (e: any) {
      console.error('获取扫描结果失败:', e);
      message.error(e.message || '获取扫描结果失败');
      setResults({ totalFiles: 0, sqlStatements: 0, problemSqlStatements: 0, issues: [] });
    } finally {
      setResultsLoading(false);
    }
  };

  // 下载Excel报告功能
  const handleDownloadExcelReport = async () => {
    if (!state.task) {
      message.warning('任务信息不完整');
      return;
    }
    
    const loadingMessage = message.loading('正在生成报告，请稍候...', 0);
    
    try {
      // 使用新的API函数下载Excel报告
      const blob = await downloadExcelReport(state.task.id);
      
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      
      // 设置默认文件名
      const fileName = `SQLCheck_Report_${state.task.taskName}_${new Date().toISOString().slice(0, 10).replace(/-/g, '')}.xlsx`;
      link.download = fileName;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      loadingMessage(); // 关闭loading消息
      message.success('报告下载成功');
    } catch (error: any) {
      loadingMessage(); // 关闭loading消息
      console.error('下载Excel报告失败:', error);
      message.error('下载报告失败：' + (error.message || '网络错误'));
    }
  };

  // 处理任务操作
  const handleTaskAction = async (action: 'start' | 'cancel' | 'retry' | 'delete' | 'download') => {
    try {
      setState(prev => ({ ...prev, actionLoading: true }));
      
      // 对于重试操作，先检查凭证
      if (action === 'retry') {
        if (!state.task) return;
        
        // 再次检查凭证有效期
        if (needsCredentialCheck(state.task)) {
          await checkCredentials(state.task);
          
          // 检查完毕后再次验证
          if (!state.credentialStatus.hasValidCredentials) {
            message.error('用户凭证已过期，无法重试任务。请重新授权后再试。');
            setState(prev => ({ ...prev, actionLoading: false }));
            return;
          }
        }
        
        // 显示重试确认对话框
        const confirmed = await new Promise<boolean>((resolve) => {
          Modal.confirm({
            title: '确认重试任务',
            content: (
              <div>
                <p>重试将重新执行整个任务，并覆盖原有的执行结果。</p>
                <p>当前重试次数: {state.task!.retryCount || 0}/{state.task!.maxRetryCount || 3}</p>
                <p>确定要继续吗？</p>
              </div>
            ),
            okText: '确认重试',
            cancelText: '取消',
            onOk: () => resolve(true),
            onCancel: () => resolve(false)
          });
        });
        
        if (!confirmed) {
          setState(prev => ({ ...prev, actionLoading: false }));
          return;
        }
      }

      switch (action) {
        case 'start':
          await startTask(Number(id));
          message.success('任务启动请求已提交，正在后台执行...');
          // 立即更新任务状态为RUNNING（乐观更新）并强制启动轮询
          setState(prev => ({ 
            ...prev, 
            task: prev.task ? { 
              ...prev.task, 
              status: 'RUNNING' as any,
              progress: 0 
            } : null 
          }));
          
          // 延迟1秒后再从后端加载真实状态，避免立即覆盖乐观更新
          setTimeout(() => {
            console.log('TaskDetail: 延迟加载任务状态');
            loadTask();
          }, 1000);
          break;
        case 'cancel':
          await cancelTask(Number(id));
          message.success('任务已取消');
          break;
        case 'retry':
          await retryTask(Number(id));
          message.success('任务重试请求已提交，正在后台执行...');
          // 立即更新任务状态为RUNNING（乐观更新）
          setState(prev => ({ 
            ...prev, 
            task: prev.task ? { 
              ...prev.task, 
              status: 'RUNNING' as any,
              progress: 0,
              errorMessage: undefined 
            } : null 
          }));
          
          // 延迟1秒后再从后端加载真实状态
          setTimeout(() => {
            console.log('TaskDetail: 延迟加载任务状态（重试）');
            loadTask();
          }, 1000);
          break;
        case 'download':
          handleDownloadExcelReport();
          return;
        case 'delete':
          message.info('删除功能开发中...');
          return;
        default:
          return;
      }
      
      // 对于启动和重试操作，不立即重新加载，让轮询机制和延迟加载处理更新
      if (action !== 'start' && action !== 'retry') {
        await loadTask();
      }
    } catch (error: any) {
      console.error('任务操作失败:', error);
      message.error(error.message || '操作失败');
      // 如果启动或重试失败，恢复任务状态
      if (action === 'start' || action === 'retry') {
        await loadTask();
      }
    } finally {
      setState(prev => ({ ...prev, actionLoading: false }));
    }
  };

  // 处理返回列表
  const handleBack = () => {
    navigate('/tasks');
  };

  // 处理刷新
  const handleRefresh = () => {
    loadTask();
  };

  // 分享功能处理函数
  const handleShare = () => {
    const currentUrl = window.location.origin;
    const publicUrl = `${currentUrl}/tasks/public/${id}`;
    
    setState(prev => ({
      ...prev,
      shareModal: {
        visible: true,
        publicUrl: publicUrl
      }
    }));
  };

  // 复制分享链接
  const handleCopyShareLink = async () => {
    try {
      await navigator.clipboard.writeText(state.shareModal.publicUrl);
      message.success('分享链接已复制到剪贴板');
    } catch (error) {
      // 兜底方案，创建临时input元素进行复制
      const tempInput = document.createElement('input');
      tempInput.value = state.shareModal.publicUrl;
      document.body.appendChild(tempInput);
      tempInput.select();
      document.execCommand('copy');
      document.body.removeChild(tempInput);
      message.success('分享链接已复制到剪贴板');
    }
  };

  // 关闭分享弹窗
  const handleCloseShareModal = () => {
    setState(prev => ({
      ...prev,
      shareModal: {
        ...prev.shareModal,
        visible: false
      }
    }));
  };




  // 加载状态
  if (state.loading) {
    return (
      <div className="loading-container">
        <Spin size="large" />
        <Text style={{ marginTop: 16, display: 'block', textAlign: 'center' }}>
          加载任务详情中...
        </Text>
      </div>
    );
  }

  // 任务不存在
  if (!state.task) {
    return (
      <div className="empty-container">
        <Empty description="任务不存在" />
        <Button type="primary" onClick={handleBack} style={{ marginTop: 16 }}>
          返回任务列表
        </Button>
      </div>
    );
  }

  const { task } = state;

  // 生成优化的任务标题 - 新格式：GIT_MYSQL2GOLDENDB_RULE_20250827_85
  const generateTaskTitle = (task: EnhancedScanTaskResponse): string => {
    const components: string[] = [];
    
    // 1. 任务类型 - 转换为简洁英文
    const taskTypeMap: Record<string, string> = {
      'GIT_SCAN': 'GIT',
      'GIT_SOURCE_SCAN': 'GIT', 
      'DATABASE_SCAN': 'DB',
      'DATABASE_DDL_SCAN': 'DDL',
      'MIXED_SCAN': 'MIXED',
      'PROJECT_SCAN': 'PROJECT',
      'MANUAL_SQL': 'MANUAL'
    };
    const taskType = taskTypeMap[task.taskType] || task.taskType;
    components.push(taskType);
    
    // 2. 源数据库类型 + 2 + 目标数据库类型
    const sourceDb = (task.sourceDbType || task.config?.sourceDbType || 'UNKNOWN').toUpperCase();
    const targetDb = (task.targetDbType || task.config?.targetDbType || 'UNKNOWN').toUpperCase();
    components.push(`${sourceDb}2${targetDb}`);
    
    // 3. 分析引擎 - 简化显示
    let engineType = 'RULE'; // 默认规则引擎
    const analysisEngine = task.analysisEngineDisplay || task.config?.analysisEngine;
    if (analysisEngine) {
      if (analysisEngine.includes('AI') || analysisEngine.includes('LLM')) {
        engineType = 'AI';
      } else if (analysisEngine.includes('混合') || analysisEngine.includes('Mixed')) {
        engineType = 'HYBRID';
      }
    }
    components.push(engineType);
    
    // 4. 创建日期 - 格式化为YYYYMMDD
    const createDate = new Date(task.createdAt);
    const dateStr = createDate.getFullYear().toString() + 
                   (createDate.getMonth() + 1).toString().padStart(2, '0') + 
                   createDate.getDate().toString().padStart(2, '0');
    components.push(dateStr);
    
    // 5. 任务ID
    components.push(task.id.toString());
    
    return components.join('_');
  };

  // 转换问题数据格式
  const convertedProblems = results?.issues ? problemDataConverter(results.issues) : [];

  return (
    <div className="task-detail">
      {/* 页面头部 */}
      <header className="page-header">
        <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={handleBack}
          size="large"
          className="back-button"
        >
          返回列表
        </Button>
        
        <div className="header-content">
          <Title level={2} className="task-title">
            {generateTaskTitle(task)}
            {isPolling && (
              <Tooltip title="正在实时监控任务状态">
                <SyncOutlined 
                  spin 
                  style={{ 
                    marginLeft: 12, 
                    fontSize: 16, 
                    color: '#1890ff' 
                  }} 
                />
              </Tooltip>
            )}
          </Title>
          <Space size="large" className="task-meta">
            <Text className="task-id">
              任务ID: #{task.id}
            </Text>
            <Text className="created-time">
              创建时间: {new Date(task.createdAt).toLocaleString()}
            </Text>
            {isPolling && (
              <Text style={{ color: '#1890ff' }}>
                实时监控中...
              </Text>
            )}
          </Space>
        </div>
        
        {/* 头部操作按钮组 */}
        <div className="header-actions">
          <Space size="middle">
            {/* 调试信息 - 可以在开发环境中显示 */}
            {/* {console.log('Task status:', task.status)} */}
            
            {/* 只有登录用户才能看到任务控制按钮 */}
            {isUserLoggedIn() && (
              <>
                {(task.status === 'PENDING' || task.status === 'CREATED' || task.status === 'PAUSED') ? (
                  <Button 
                    type="primary" 
                    onClick={() => handleTaskAction('start')}
                    loading={state.actionLoading}
                    size="large"
                    className="action-button"
                  >
                    启动任务
                  </Button>
                ) : task.status === 'RUNNING' ? (
                  <Button 
                    type="default"
                    danger
                    onClick={() => handleTaskAction('cancel')}
                    loading={state.actionLoading}
                    size="large"
                    className="action-button"
                  >
                    取消任务
                  </Button>
                ) : null}
                
                {task.status === 'FAILED' && (
                  <Button 
                    type="primary"
                    onClick={() => handleTaskAction('retry')}
                    loading={state.actionLoading}
                    size="large"
                    className="action-button"
                  >
                    重试任务
                  </Button>
                )}
                
                {/* 扩展的重试按钮 - 支持更多状态和凭证检查 */}
                {canRetryWithCredentials(task) && task.status !== 'FAILED' && (
                  <Tooltip 
                    title={
                      !state.credentialStatus.hasValidCredentials && needsCredentialCheck(task) 
                        ? '用户凭证已过期，无法重试' 
                        : '重新执行任务，将覆盖原有任务信息'
                    }
                  >
                    <Button 
                      type="default"
                      onClick={() => handleTaskAction('retry')}
                      loading={state.actionLoading || state.credentialStatus.loading}
                      disabled={!state.credentialStatus.hasValidCredentials && needsCredentialCheck(task)}
                      size="large"
                      className="action-button"
                    >
                      重新执行
                    </Button>
                  </Tooltip>
                )}
              </>
            )}
            
            <Button 
              onClick={handleRefresh}
              size="large"
              className="action-button"
            >
              刷新
            </Button>

            {/* 分享按钮 - 所有用户都可以看到 */}
            <Tooltip title="生成公开分享链接，任何人都可以通过此链接查看任务详情">
              <Button 
                icon={<ShareAltOutlined />}
                onClick={handleShare}
                size="large"
                className="action-button"
              >
                分享
              </Button>
            </Tooltip>
            
            {(task.status === 'COMPLETED' || task.status === 'SUCCESS') && (
              <Button 
                onClick={() => handleTaskAction('download')}
                size="large"
                className="action-button"
              >
                下载报告
              </Button>
            )}
          </Space>
          
          {/* 凭证状态提示 - 移动到按钮组下方 */}
          {needsCredentialCheck(task) && canRetryWithCredentials(task) && task.status !== 'FAILED' && (
            <div style={{ marginTop: 12, textAlign: 'center' }}>
              {state.credentialStatus.loading ? (
                <Text type="secondary" style={{ fontSize: '12px', color: 'rgba(255, 255, 255, 0.85)' }}>
                  <SyncOutlined spin /> 检查凭证...
                </Text>
              ) : state.credentialStatus.hasValidCredentials ? (
                <Text type="success" style={{ fontSize: '12px', color: '#52c41a' }}>
                  ✓ 凭证有效
                </Text>
              ) : (
                <Text type="warning" style={{ fontSize: '12px', color: '#faad14' }}>
                  ⚠ 凭证无效
                </Text>
              )}
            </div>
          )}
        </div>
      </header>

      {/* 主体内容 - 三部分清晰布局 */}
      <main className="main-content">
        
        {/* 第一部分：任务执行信息 */}
        <section className="section-execution">
          <div className="section-header">
            <Title level={3}>任务执行信息</Title>
            <Text type="secondary">任务配置、启停时间、进度信息</Text>
          </div>
          <div className="execution-content">
            <TaskExecutionInfo task={task} progressInfo={state.progressInfo} />
          </div>
        </section>

        {/* 第二部分：扫描结果 */}
        <section className="section-scan-results">
          <div className="section-header">
            <Title level={3}>扫描结果</Title>
            <Text type="secondary">
              {task.taskType === 'GIT_SCAN' ? 'Git仓库扫描分析结果' :
               task.taskType === 'DATABASE_SCAN' ? '数据库DDL扫描分析结果' : 
               task.taskType === 'MIXED_SCAN' ? '混合扫描分析结果' :
               '任务扫描分析结果'}
              {(task.status === 'COMPLETED' || task.status === 'SUCCESS') && results && 
                ` · 共发现 ${results.issues?.length || 0} 个兼容性问题`
              }
            </Text>
          </div>
          
          {/* 任务统计信息子区域 */}
          <div className="sub-section-statistics">
            <TaskStatistics task={task} scanResults={results} />
          </div>
          
          {/* 问题清单子区域 */}
          {(task.status === 'COMPLETED' || task.status === 'SUCCESS') && (
            <div className="sub-section-problems">
              <div className="sub-section-header">
                <Title level={4} style={{ margin: 0, color: '#1890ff' }}>问题清单</Title>
                <Text type="secondary" style={{ fontSize: 12 }}>详细的兼容性问题列表</Text>
              </div>
              {results && convertedProblems.length > 0 ? (
                <div className="problem-list-section">
                  <EnhancedProblemTable
                    problems={convertedProblems}
                    height={600}
                    taskConfig={state.task?.config}
                    onApplySuggestion={(issue) => {
                      message.info('应用修复建议功能开发中...');
                    }}
                    onBatchApply={(issues) => {
                      message.info(`批量应用 ${issues.length} 个修复建议功能开发中...`);
                    }}
                  />
                </div>
              ) : results && convertedProblems.length === 0 ? (
                <div className="no-problems-container">
                  <Empty
                    description="🎉 恭喜！未发现兼容性问题"
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                  />
                </div>
              ) : resultsLoading ? (
                <div className="loading-container">
                  <Spin size="large" />
                  <Text style={{ marginTop: 16, display: 'block', textAlign: 'center' }}>
                    正在加载扫描结果...
                  </Text>
                </div>
              ) : null}
            </div>
          )}
          
          {/* 未完成任务的提示 */}
          {task.status !== 'COMPLETED' && task.status !== 'SUCCESS' && (
            <div className="pending-content">
              <div className="pending-results-container">
                <Empty
                  description={
                    task.status === 'RUNNING' || task.status === 'PROCESSING' ? 
                    '任务正在执行中，完成后将显示详细结果' :
                    task.status === 'FAILED' ? '任务执行失败，请重试' :
                    '等待任务执行完成'
                  }
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
              </div>
            </div>
          )}
        </section>
        
      </main>

      {/* 分享弹窗 */}
      <Modal
        title={
          <Space>
            <ShareAltOutlined />
            分享任务详情
          </Space>
        }
        open={state.shareModal.visible}
        onCancel={handleCloseShareModal}
        footer={[
          <Button key="close" onClick={handleCloseShareModal}>
            关闭
          </Button>,
          <Button 
            key="copy" 
            type="primary" 
            icon={<CopyOutlined />}
            onClick={handleCopyShareLink}
          >
            复制链接
          </Button>
        ]}
        width={600}
      >
        <div style={{ padding: '16px 0' }}>
          <div style={{ marginBottom: 16 }}>
            <Text type="secondary">
              通过以下公开链接，任何人都可以查看此任务的详细信息（无需登录）：
            </Text>
          </div>
          
          <div 
            style={{ 
              padding: '12px 16px',
              backgroundColor: '#f5f5f5',
              border: '1px solid #d9d9d9',
              borderRadius: 6,
              wordBreak: 'break-all',
              fontFamily: 'monospace',
              fontSize: '14px'
            }}
          >
            {state.shareModal.publicUrl}
          </div>
          
          <div style={{ marginTop: 16 }}>
            <Text type="secondary" style={{ fontSize: 12 }}>
              💡 提示：此链接可以直接分享给同事或保存在文档中，无需额外的权限配置
            </Text>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default TaskDetail;